import http from '@/utils/http'
import {configStore} from "@/store/config";
import {userLogsStore} from "@/store/logs"

import {formatHgaTime, formatHttpUrl, formatRECount, formatTime, replaceTeamName, trim, utf16to8, delay} from "@/utils/utils";
import {createOrder, createHgaOrder} from "@/api/tdc_api";

const qs = require("qs");
const path = require('path');
const fs = require('fs');
const { XMLParser} = require("fast-xml-parser");
const configUserStore = configStore();

let storeLogs = userLogsStore();


let HOST = formatHttpUrl(configUserStore.setting.hga_url);

/// 去页面用正则匹配所需变量
async function mainRequest(param = {'detection': 'Y'}, method = 'POST', domain = '') {
	let url = '/';

	HOST = formatHttpUrl(configUserStore.setting.hga_url);

	if (domain) {
		url = 'https://' + domain + url;
	} else {
		url = HOST + url;
	}
	let res = await http.post(url, qs.stringify(param));
	if(!res) {
		return false;
	}
	var div = document.createElement("div");
	div.innerHTML = res;
	let indexJS = div.querySelector("#indexJS").innerHTML;
	const regex = /top\.(\w+)\s*=\s*'([^']+)'/gm; // 匹配一个或多个数字，多行匹配
	const matches = indexJS.match(regex);

	const regex2 = /top.iovationCount\s*=\s*([0-9]+)/gm
	const matches2 = indexJS.match(regex2);
	if(matches2 && matches2.length) {
		matches.push(matches2[0]);
	}

	let result = {};
	matches.forEach((str) => {
		let m = str.split("=");
		let key =  m[0].replaceAll("top.", "").replace(/^\s+|\s+$/g, "");
		let value = m[1].replaceAll("'",'').replace(/^\s+|\s+$/g, "");
		result[key] = value;
	})
	return result;
}

/// 缓存用户信息
let userInfoApi = (function () {
	const filePath = path.join(__lib, 'hag_user_info.json');
	return {
		save:function (userInfo) {
			fs.writeFileSync(filePath, JSON.stringify(userInfo, null, 2));
		},
		get:function () {
			try{
				return  JSON.parse( fs.readFileSync(filePath, 'utf8'));
			}catch (e){
				return {};
			}
		}
	}
})();

let formatGameDataList = function (res = {}){
	let gameList = [];
	if(res['dataCount']) {
		if(res['ec']['game']) {
			gameList.push(res['ec']['game']);
		}else {
			res['ec'].forEach((item) => {
				gameList.push(item['game']);
			})
		}
	}else {
		return gameList;
	}

	/// 通用下注配置
	let buy_data_common = {
		"golds": 50,
		"autoOdd": "Y",
		"isRB": "Y",
		"isYesterday": "N",
		"f": "1R",
		"odd_f_type": "H",
		"gtype": "FT",
	};

	let newGameList = [];

	let keysList = {
		'RATIO_R': 'RATIO_RE', // 全场让球
		'IOR_RH': 'IOR_REH',
		'IOR_RC': 'IOR_REC',
		'RATIO_OUO': 'RATIO_ROUO', // 全场大小球
		'RATIO_OUU': 'RATIO_ROUU',
		'IOR_OUH': 'IOR_ROUH',
		'IOR_OUC': 'IOR_ROUC',
		'RATIO_HR': 'RATIO_HRE', // 上半场让球
		'IOR_HRH': 'IOR_HREH',
		'IOR_HRC': 'IOR_HREC',
		'RATIO_HOUO': 'RATIO_HROUO', // 上半场大小球
		'RATIO_HOUU': 'RATIO_HROUU',
		'IOR_HOUH': 'IOR_HROUH',
		'IOR_HOUC': 'IOR_HROUC'
	};

	gameList.forEach((item) => {

		for(let key in keysList) {
			if(typeof item[key] != 'undefined') {
				let _key = keysList[key];
				item[_key] = item[key];
			}
		}
		/*
		item['RATIO_RE'] = item['RATIO_R'];
		item['IOR_REH'] = item['IOR_RH'];
		item['IOR_REC'] = item['IOR_RC'];
		item['RATIO_ROUO'] = item['RATIO_OUO'];
		item['RATIO_ROUU'] = item['RATIO_OUU'];
		item['IOR_ROUH'] = item['IOR_OUH'];
		item['IOR_ROUC'] = item['IOR_OUC'];
		item['RATIO_HRE'] = item['RATIO_HR'];
		item['IOR_HREH'] = item['IOR_HRH'];
		item['IOR_HREC'] = item['IOR_HRC'];
		item['RATIO_HROUO'] = item['RATIO_HOUO'];
		item['RATIO_HROUU'] = item['RATIO_HOUU'];
		item['IOR_HROUH'] = item['IOR_HOUH'];
		item['IOR_HROUC'] = item['IOR_HOUC'];
		*/

		item['MG'] = formatHgaTime(item['DATETIME']);

		let datetime_int = item['MG'];
		let newTime = +new Date(item['SYSTIME']);
		newTime += (12 * 3600 * 1000);
		let diff_time = ~~((datetime_int - newTime)/1000);
		let retimeset = item['RETIMESET']||"";
		if(diff_time < 0 && retimeset) {
			let pattern = /(1H|2H)/g;
			if(pattern.exec(retimeset)) {
				let reTimeStr = retimeset.split("^");
				if(reTimeStr.length === 2) {
					let timeComponents = reTimeStr[1].split(":");
					let minutes = timeComponents[0] * 1;
					let seconds = timeComponents[1] * 1;
					diff_time = (minutes * 60) + seconds;
					diff_time *= -1;
				}
			}else {
				diff_time = -9999999;
			}
		}
		item['TEAM_H'] = replaceTeamName(item['TEAM_H']);
		item['TEAM_C'] = replaceTeamName(item['TEAM_C']);

		let tempData = {};
		tempData["competition"] = {
			'time_str': formatTime(datetime_int),
			'datetime_int': datetime_int,
			'gid': item['GID'],
			'lid': item['LID'],
			"league": item['LEAGUE'],
			'ecid': item['ECID'],
			"ecName": item['TEAM_H'] + " VS " + item['TEAM_C'],
			'team_h': item['TEAM_H'],
			'team_c': item['TEAM_C'],
			'retimeset': item['RETIMESET'],
			"diff_time": diff_time,
			"diff_time_type": (diff_time <= 0) ? "doing" : "warn",
			'score_h_c': (item['SCORE_H']||0)  +  "-" + (item['SCORE_C']||0),
			'systime':formatTime(newTime),
		};

		/// 全场让球
		if(item['IOR_REH'] || item['IOR_REC']) {
			tempData['concede_points'] = {
				"betHdp_h": formatRECount(item['RATIO_RE']),
				"betHdp_c": formatRECount(item['RATIO_RE']),
				"odds_h": item['IOR_REH'] * 1,
				"odds_c": item['IOR_REC'] * 1,
				"buy_data": {
					"h": {
						...buy_data_common,
						"wtype": "RE",
						"rtype": "REH",
						"chose_team": "H",
						"gid": item['GID'],
					},
					"c": {
						...buy_data_common,
						"wtype": "RE",
						"rtype": "REC",
						"chose_team": "C",
						"gid": item['GID'],
					},
					"warn_h": {
						...buy_data_common,
						"wtype": "R",
						"rtype": "RH",
						"chose_team": "H",
						"gid": item['GID'],
					},
					"warn_c": {
						...buy_data_common,
						"wtype": "R",
						"rtype": "RC",
						"chose_team": "C",
						"gid": item['GID'],
					}
				}
			};

			if(item['STRONG'] === 'H') {
				tempData['concede_points']['betHdp_h'] *= -1;
			}else {
				tempData['concede_points']['betHdp_c'] *= -1;
			}
		}
		/// 全场大小球
		if(item['IOR_ROUH'] || item['IOR_ROUC']) {
			tempData['min_big'] = {
				"betHdp_c": formatRECount(item['RATIO_ROUO']), // UO和UU未有办法区分客队或客队
				"betHdp_h": formatRECount(item['RATIO_ROUU']), // UO和UU未有办法区分客队或客队
				"odds_c": item['IOR_ROUH'] * 1,
				"odds_h": item['IOR_ROUC'] * 1,
				"buy_data": {
					"c": {
						...buy_data_common,
						"wtype": "ROU",
						"rtype": "ROUH",
						"chose_team": "H",
						"gid": item['GID'],
					},
					"h": {
						...buy_data_common,
						"wtype": "ROU",
						"rtype": "ROUC",
						"chose_team": "C",
						"gid": item['GID'],
					},
					"warn_c": {
						...buy_data_common,
						"wtype": "OU",
						"rtype": "OUH",
						"chose_team": "H",
						"gid": item['GID'],
					},
					"warn_h": {
						...buy_data_common,
						"wtype": "OU",
						"rtype": "OUC",
						"chose_team": "C",
						"gid": item['GID'],
					}
				}
			};
		}

		/// 上半场让球
		if(item['IOR_HREH'] || item['IOR_HREC']) {
			tempData['r_concede_points'] = {
				"betHdp_h": formatRECount(item['RATIO_HRE']),
				"betHdp_c": formatRECount(item['RATIO_HRE']),
				"odds_h": item['IOR_HREH'] * 1,
				"odds_c": item['IOR_HREC'] * 1,
				"buy_data": {
					"h": {
						...buy_data_common,
						"wtype": "HRE",
						"rtype": "HREH",
						"chose_team": "H",
						"gid": item['HGID']
					},
					"c": {
						...buy_data_common,
						"wtype": "HRE",
						"rtype": "HREC",
						"chose_team": "C",
						"gid": item['HGID']
					},
					"warn_h": {
						...buy_data_common,
						"wtype": "HR",
						"rtype": "HRH",
						"chose_team": "H",
						"gid": item['HGID']
					},
					"warn_c": {
						...buy_data_common,
						"wtype": "HR",
						"rtype": "HRC",
						"chose_team": "C",
						"gid": item['HGID']
					}
				},
			};
			if(item['HSTRONG'] === 'H') {
				tempData['r_concede_points']['betHdp_h'] *= -1;
			}else {
				tempData['r_concede_points']['betHdp_c'] *= -1;
			}
		}

		/// 上半场大小球
		if(item['IOR_HROUH'] || item['IOR_HROUC']) {
			tempData['r_min_big'] = {
				"betHdp_c": formatRECount(item['RATIO_HROUO']), // UO和UU未有办法区分客队或客队
				"betHdp_h": formatRECount(item['RATIO_HROUU']), // UO和UU未有办法区分客队或客队
				"odds_c": item['IOR_HROUH'] * 1,
				"odds_h": item['IOR_HROUC'] * 1,
				"buy_data": {
					"c": {
						...buy_data_common,
						"wtype": "HROU",
						"rtype": "HROUH",
						"chose_team": "H",
						"gid": item['HGID']
					},
					"h": {
						...buy_data_common,
						"wtype": "HROU",
						"rtype": "HROUC",
						"chose_team": "C",
						"gid": item['HGID']
					},
					"warn_c": {
						...buy_data_common,
						"wtype": "HOU",
						"rtype": "HOUH",
						"chose_team": "H",
						"gid": item['HGID']
					},
					"warn_h": {
						...buy_data_common,
						"wtype": "HOU",
						"rtype": "HOUC",
						"chose_team": "C",
						"gid": item['HGID']
					}
				},
			};
		}
		newGameList.push(tempData);
	})
	newGameList = newGameList.sort(function (a, b) {
		if(a['competition']['datetime_int'] === b['competition']['datetime_int']) {
			return 0;
		}
		return a['competition']['datetime_int'] > b['competition']['datetime_int'] ? 1 : -1;
	})
	return newGameList;
}

const parser = new XMLParser();
/// 通用接口请求
async function transformRequest(params = {}, domain = '', addVer = false) {

	let url = '/transform.php';
	if (domain) {
		if(domain === 'no') {
			url = HOST + url;
		}else {
			url = domain + url;
		}
	} else {
		url = (configUserStore.hga_domain_url || HOST) + url;
	}
	if(params['ver']) {
		url += "?ver=" + params['ver'];
	}
	let res = await http.post(url, qs.stringify( {'p':'chk_login', ...params}));
	if (!res) {
		return false;
	}
	try {
		let result = parser.parse(res);
		return result['serverresponse']||result['serverrequest']||null;
	}catch (e){
		console.log(e);
		return null;
	}
}

/// HGA 登录
export const toHgaLogin = async function (data) {
  	let _top = await mainRequest();
	if(!_top) {
		return {
			'state': 0,
			'message': "login error"
		}
	}
	let loginInfo = await transformRequest({
		'langx': _top['langx'],
		'ver': _top['ver'],
		'app': _top['isapp'],
		'auto': _top['iovationKey'],
		'blackbox': _top['blackbox'] || '',
		'userAgent': btoa(utf16to8(configUserStore.setting.bet_user_agent)),
		...data,
	}, 'no');
	if(!loginInfo) {
		return {
			'state': 0,
			'message': "login error"
		}
	}
	let uid = loginInfo['uid'];
	if(!uid || loginInfo['status'] !== 200) {
		return {
			'state': 0,
			'data': loginInfo,
			'message': 'login error'
		}
	}

	let domainData = await transformRequest({
		'username': loginInfo['username'],
		'uid': uid,
		'langx': _top['langx'],
		'ver': _top['ver'],
		'code': 663,
		'p': 'check_login_domain'
	}, "no");
	if(!domainData['new_domain'] || domainData['new_domain'] === 'no') {
		return {
			'state': 0,
			'data': domainData,
			'message': 'login error'
		}
	}

	let _domain = domainData['new_domain'];
	if(_domain.indexOf('http') === -1) {
		_domain = "https://" + _domain;
	}

	let userInfo = {
		'uid': uid,
		'ver': _top['ver'],
		'username': loginInfo['username'],
		'pay_type': loginInfo['pay_type'],
		'passwd_safe': loginInfo['username'],
		'odd_f': loginInfo['odd_f'],
		'msg': loginInfo['msg'],
		'mid': loginInfo['mid'],
		'ltype': loginInfo['ltype'],
		'currency': loginInfo['currency'],
		'domain': loginInfo['domain'],
		'domain_url': _domain,
		'blackBoxStatus': loginInfo['blackBoxStatus'],
		'langx': _top['langx'],
		'iovationCnt': _top['iovationCount']||0,
		'odd_f_type': 'H',
		'cuipv6': 'N',
		'ipv6': 'Y',
		'cu': 'N',
		'four_pwd': 'new',
		'abox4pwd_notshow': 'N', // 读cookie (CookieManager.get("box4pwd_notshow_" + top["userData"].mid)).split('_')[1]
	}

	configUserStore.updateHgaDomainUrl(_domain);

	userInfoApi.save(userInfo);

	return  {
		'state': 1,
		'data': userInfo,
		'message': 'login suc'
	}
}

/// HGA 用户信息
export const getHgaBalance = async function(){
	let userInfo = userInfoApi.get();
	if(!userInfo['uid']) {
		return {
			'state': 0,
			'message': 'userinfo empty'
		}
	}
	let memberData = await transformRequest({
		'p': 'get_member_data',
		'uid': userInfo['uid'],
		'ver': userInfo['ver'],
		'langx': userInfo['langx'],
		'change': 'all',
	}, userInfo['domain_url']);
	if(typeof memberData['maxcredit'] != 'undefined') {
		return {
			'state': 1,
			'data': {
				...userInfo,
				...memberData
			},
			'message': 'balance suc'
		}
	}
	return {
		'state': 0,
		'data': memberData,
		'message': 'balance error'
	}
}

/// 获取HGA 滚球游戏列表，也就是比赛中的游戏列表
export const loadHgaDoingGameList = async function() {
	let userInfo = userInfoApi.get();
	/// 滚球
	let gameListParam = {
		'uid': userInfo['uid'],
		'ver': userInfo['ver'],
		'langx': userInfo['langx'],
		'p': 'get_game_list',
		'p3type': '',
		'date': '',
		'gtype': 'ft',
		'showtype': 'live',
		'rtype': 'rb',
		'ltype': userInfo['ltype'],
		// 'filter': '',
		'cupFantasy': 'N',
		'sorttype': 'L',
		'specialClick': '',
		'isFantasy': 'N',
		'ts': +new Date(),
	};
	let res = await transformRequest(gameListParam, userInfo['domain_url']);
	if(res) {
		if(res.code === 'error') {
			return {
				'state': 0,
				'data': res,
				'message': 'load gameList error'
			}
		}
		let gameList = formatGameDataList(res);
		return {
			'state': 1,
			'data': gameList,
			'message': 'load gameList suc'
		}
	}else {
		return {
			'state': 0,
			'data': res,
			'message': 'load gameList error'
		}
	}
}

/// 获取HGA 游戏列表
export const loadHgaGameList = async function () {
	let userInfo = userInfoApi.get();
	/// 未开赛
	let gameListParam = {
		'p': 'get_game_list',
		'ver': userInfo['ver'],
		'uid': userInfo['uid'],
		'langx': userInfo['langx'],
		'p3type': '',
		'date': 0,
		'showtype': 'today',
		'gtype': 'ft',
		'rtype': 'r',
		'ltype': userInfo['ltype'],
		'cupFantasy': 'N',
		'lid': '',
		'field': 'cp1',
		'action': 'clickCoupon',
		'sorttype': 'L',
		'specialClick': ' ',
		'isFantasy': 'N',
		'ts': +new Date(),
	};
	let res = await transformRequest(gameListParam, userInfo['domain_url']);
	if(res) {
		if(res.code === 'error') {
			return {
				'state': 0,
				'data': res,
				'message': 'load gameList error'
			}
		}
		let gameList = formatGameDataList(res);
		return {
			'state': 1,
			'data': gameList,
			'message': 'load gameList suc'
		}
	}else {
		return {
			'state': 0,
			'data': res,
			'message': 'load gameList error'
		}
	}
}

/**
 * 下注
 * @param data
 * @param bet_data
 * @param config
 * @param hga_team
 * @param has_agreement
 * @param one_key
 * @param bet_info
 */
export const betHgaOrder = async function(data, bet_data, config, hga_team, has_agreement, one_key, bet_info = {}) {
	let userInfo = userInfoApi.get();
	if(!userInfo['uid']) {
		return {
			'state': 0,
			'message': 'userinfo empty'
		}
	}

	/// 原始下注金额
	let original_bet_amount = bet_data['original_bet_amount']*1;
	/// 原始盘口
	let bet_hdp = bet_data['bet_hdp'] * 1;
	/// 已下注次数
	let init_bet_count = 1;
	// 已下注金额
	let total_bet_amount = 0;
	/// 失败重试次数
	let error_bet_count = 1;
	/// 定时器 重试时间和补单时间
	let timeLength = config['bet_interval_time'] * 1000;
	/// 通过这个来更新 下注金额

	/// 最多下几次
	let max_bet_count = config['bet_max_count'];

	total_bet_amount = original_bet_amount;

	let gtype = "FT";

	let dataTempList = [];

	let betOrderFun = async function () {
		if (init_bet_count > max_bet_count) {
			console.error('超过同盘口注单数量：' + max_bet_count);
			return {
				'state': 0,
				'message': 'max_bet_count error'
			};
		}
		if (total_bet_amount < 50) {
			total_bet_amount = 50;
		}
		let FT_order_view = {
			'p': 'FT_order_view', // FT_order_view 足球 Other_order_view 篮球
			'ver': userInfo['ver'],
			'uid': userInfo['uid'],
			'langx': userInfo['langx'],
			'odd_f_type': 'H',
			'gid': data['gid'],
			'gtype': 'FT',  // FT 足球 BK 篮球
			'wtype': data['wtype'],
			'chose_team': data['chose_team'],
		}

		let orderData = {
			"order_id":"",
			"bet_id": -9,
			'options' : {...data},
			'amount': data['golds'],
			'domain': "hga",
			'device': "app",
			'status': -9999,
			'status_name': "",
			'has_diff': "",
			'hc_type': 9,
			'hga_team': {...hga_team},
			'one_key': one_key||"",
		};

		let res = await transformRequest(FT_order_view, userInfo['domain_url']);
		if(res && res['aid']) {

			console.log(['FT_order_view', res]);
			storeLogs.add(JSON.stringify(res));
			let conList = res['spread'].toString().split("/");

			if(conList.length === 2) {
				conList = (((trim(conList[0]) * 1) + (trim(conList[1]) * 1) )/2).toFixed(2);
				conList *= 1;
			}else  {
				conList = conList[0] * 1;
			}

			/// 独赢 盘口为0;
			if(FT_order_view['wtype'] === 'RM' || FT_order_view['wtype'] === 'HRM' ) {
				conList = 0;
			}

			if(data['chose_team'] === res['strong']) {
				if(bet_hdp < 0) {
					conList *= -1;
				}
			}

			if(has_agreement) {
				let has_bet_hdp = false;
				if(bet_hdp == conList) {
					has_bet_hdp = true;
				}else {
					/// 接受最佳盘口
					/// 水位要大于设置的最低盘口
					let wtype = data['wtype'];
					/// 让球 和 受球
					if(wtype === 'RE' || wtype === 'HRE') {
						/// 原让 -1 球 ，现变成让 -0.75 球，可以进行下注
						if(conList <= 0 && bet_hdp <= 0) {
							if(conList > bet_hdp) {
								has_bet_hdp = true;
							}
						}
						/// 原受 1 球 ，现变成受 1.25 球，可以进行下注
						if(conList >= 0 && bet_hdp >= 0) {
							if(conList > bet_hdp) {
								has_bet_hdp = true;
							}
						}
					}
					console.error(['data', data]);
					/// 大球 和 小球
					if(wtype === 'ROU' || wtype === 'HROU') {
						// 原大 2 球，现变成大 1.75 可以进行下注
						/// C 是大球
						if(data['chose_team'] === 'C') {
							if(bet_hdp > conList) {
								has_bet_hdp = true;
							}
						}
						// 原小 2 球，现变成小 2.15 可以进行下注
						/// H 是小球
						if(data['chose_team'] === 'H') {
							if(conList > bet_hdp) {
								has_bet_hdp = true;
							}
						}
					}
				}
				if(!has_bet_hdp) {
					return {
						'state': 0,
						'dataTempList': dataTempList,
						'message': `hdp != error ${bet_hdp} _ ${conList}`
					}
				}
			}else {
				if(bet_hdp !== conList) {
					return {
						'state': 0,
						'dataTempList': dataTempList,
						'message': `hdp != error ${bet_hdp} _ ${conList}`
					}
				}
			}


			/// 下单开始
			const form_data = {
				'p': 'FT_bet',  // FT_bet 足球 Other_bet 篮球
				'ver': userInfo['ver'],
				'uid': userInfo['uid'],
				'langx': userInfo['langx'],
				'odd_f_type': 'H',
				'golds': data['golds'],  // 下注金额
				'gid': FT_order_view['gid'],
				'gtype': FT_order_view['gtype'],  // 足球
				'wtype': data['wtype'],        // RE
				'rtype': data['wtype'] + data['chose_team'],        // REH REC   H/C 与 chose_team
				'chose_team': data['chose_team'],    // H / C  主客
				'ioratio': res['ioratio'], //FT_order_view > ioratio
				'con': res['con'],        //FT_order_view > con
				'ratio': res['ratio'],        //FT_order_view > ratio
				'autoOdd': 'Y',  //默认 Y，top["memSet"]["betterOdds"] == false ? "N" : "Y";
				'timestamp2': res['ts'],
				'timestamp': new Date().getTime(),
				'isRB': 'Y',        // isRBWtype(wtype)
				'imp': res['important'],    //FT_order_view >  important
				'ptype': res['ptype'],    //FT_order_view >  ptype
				'isYesterday': 'N',        // 默认 N
				'f':'1R',
			}

			form_data['golds'] = total_bet_amount;

			let gold_gmax = res['gold_gmax'];

			/*** 测试代码 ***/
			// gold_gmax = 50;
			/*** 测试代码 ***/

			orderData['options'] = {...form_data};
			orderData['options']['gold_gmax'] = gold_gmax;

			let hasDoing = false;
			if(hga_team && hga_team['diff_time_type'] === 'doing') {
				hasDoing = true;
			}


			/// 不超过最低限额金额不进行下单
			/// 赛前
			let bet_min_amount = config['bet_min_amount'];
			// 滚球
			if(hasDoing) {
				bet_min_amount = config['doing_bet_min_amount'];
			}
			/// 赛前
			if(gold_gmax < bet_min_amount) {
				orderData['status'] = -101;
				// createOrder(orderData, has_agreement);
				return {
					'code': 101,
					'state': 0,
					'data': res,
					'dataTempList': dataTempList,
					'message': `bet_min_amount ${bet_min_amount} _ ${gold_gmax} `
				}
			}


			/// 协议跟单不需要判断水位
			if(!has_agreement) {
				/// 赛前
				let bet_min_odds = config['bet_min_odds'];
				if(hasDoing) {
					// 滚球
					bet_min_odds = config['doing_bet_min_odds'];
				}
				/// 水位要超过最低水位
				if( bet_min_odds > res['ioratio']*1) {
					return {
						'code': 102,
						'state': 0,
						'data': res,
						'dataTempList': dataTempList,
						'message': `bet_min_odds ${config['bet_min_odds']} _ ${res['ioratio']} `
					}
				}
			}


			if(gold_gmax && total_bet_amount > gold_gmax) {
				gold_gmax *= 1;
				form_data['golds'] = (~~(gold_gmax / 50 )) * 50;
			}



			let res2 = await transformRequest(form_data, userInfo['domain_url']);
			if(res2 && res2['ticket_id']) {

				orderData['status'] = 'suc';
				orderData['order_id'] = res2['ticket_id'];
				orderData['bet_result'] = res2;
				orderData['bet_info_data'] = {...bet_info};

				createOrder(orderData, has_agreement);


				total_bet_amount -= form_data['golds'];
				console.log('下注成功', res2);

				dataTempList.push(res2);

				if(init_bet_count <= max_bet_count && total_bet_amount > 0) {
					/// 还需要继续补单
					await delay(timeLength);
					init_bet_count += 1;
					return await betOrderFun();
				}else {
					storeLogs.add(JSON.stringify({'state':1, 'data': res2}));
					return {
						'state': 1,
						'data': res2,
						'message': 'suc',
						'dataTempList': dataTempList,
					}
				}
			}else {

				orderData['status'] = -999;

				// createOrder(orderData, has_agreement);

				if(error_bet_count <= 3) {
					await delay(timeLength);
					console.error('重试次数：' + error_bet_count);
					storeLogs.add(JSON.stringify({'state':0, 'data': res2}));
					// console.error(res2);
					/// 失败需要重试
					error_bet_count += 1;
					return await betOrderFun();
				}else {
					return {
						'code': 103,
						'state': 0,
						'message': 'FT_bet max_error',
						'data': res2,
						'dataTempList': dataTempList,
					}
				}
			}
		} else {
			if(error_bet_count <= 3) {
				await delay(timeLength);
				console.error('重试次数：' + error_bet_count);
				error_bet_count += 1;
				return await betOrderFun();
			}else {
				return  {
					'code': 104,
					'state': 0,
					'data':  res,
					'message': 'FT_order_view max_error',
					'dataTempList': dataTempList,
				}
			}
		}
	}

	return await betOrderFun();
}

/**
 * 协议下注
 * @param data
 * @param config
 * @returns {Promise<void>}
 */
export const betAgreementHgaOrder = async function(data, config){
	let userInfo = userInfoApi.get();
	if(!userInfo['uid']) {
		return {
			'state': 0,
			'message': 'userinfo empty'
		}
	}

	/// 已下注次数
	let init_bet_count = 1;
	// 已下注金额
	let total_bet_amount = data['golds'] || data['gold'];
	/// 失败重试次数
	let error_bet_count = 1;
	/// 最大重试次数
	let bet_error_max_count = config['bet_error_max_count'] || 3;
	/// 定时器 重试时间和补单时间
	let timeLength = config['bet_interval_time'] * 1000;
	/// 通过这个来更新 下注金额

	/// 最多下几次
	let max_bet_count = config['bet_max_count'];


	let chose_team = data['rtype'].replace(data['wtype'], "");


	let betOrderFun = async function () {
		if (init_bet_count > max_bet_count) {
			console.error('超过同盘口注单数量：' + max_bet_count);
			return {
				'state': 0,
				'message': 'max_bet_count error'
			};
		}
		if (total_bet_amount < 50) {
			total_bet_amount = 50;
		}
		let FT_order_view = {
			'p': 'FT_order_view', // FT_order_view 足球 Other_order_view 篮球
			'ver': userInfo['ver'],
			'uid': userInfo['uid'],
			'langx': userInfo['langx'],
			'odd_f_type': 'H',
			'gid': data['gid'],
			'gtype': 'FT',  // FT 足球 BK 篮球
			'wtype': data['wtype'],
			'chose_team':  chose_team,
		}
		/// 获取盘口
		let res = await transformRequest(FT_order_view, userInfo['domain_url']);
		if(res && res['aid']) {
			/// 下单开始
			const form_data = {
				'p': 'FT_bet',  // FT_bet 足球 Other_bet 篮球
				'ver': userInfo['ver'],
				'uid': userInfo['uid'],
				'langx': userInfo['langx'],
				'odd_f_type': 'H',
				'golds': data['golds'] || data['gold'],  // 下注金额
				'gid': FT_order_view['gid'],
				'gtype': FT_order_view['gtype'],  // 足球
				'wtype': data['wtype'],        // RE
				'rtype': data['rtype'],        // REH REC   H/C 与 chose_team
				'chose_team': chose_team,    // H / C  主客
				'ioratio': res['ioratio'], //FT_order_view > ioratio
				'con': res['con'],        //FT_order_view > con
				'ratio': res['ratio'],        //FT_order_view > ratio
				'autoOdd': 'Y',  //默认 Y，top["memSet"]["betterOdds"] == false ? "N" : "Y";
				'timestamp2': res['ts'],
				'timestamp': new Date().getTime(),
				'isRB': 'Y',        // isRBWtype(wtype)
				'imp': res['important'],    //FT_order_view >  important
				'ptype': res['ptype'],    //FT_order_view >  ptype
				'isYesterday': 'N',        // 默认 N
				'f':'1R',
			}
			let gold_gmax = res['gold_gmax'];
			if(process.env.NODE_ENV === 'development') {
				// gold_gmax = 50;
			}

			form_data['golds'] = total_bet_amount;

			if(gold_gmax && total_bet_amount > gold_gmax) {
				gold_gmax *= 1;
				form_data['golds'] = (~~(gold_gmax / 50 )) * 50;
			}


			let res2 = await transformRequest(form_data, userInfo['domain_url']);
			if(res2 && res2['ticket_id']) {
				total_bet_amount -= form_data['golds'];
				console.error('Agreement 下注成功', res2);
				storeLogs.add(JSON.stringify({'state':1, 'data': res2, 'agreement': 1}));


				return {
					'state': 1,
					'data': res2,
					'message': 'Agreement suc',
				}

				if(init_bet_count <= max_bet_count && total_bet_amount > 0) {
					/// 还需要继续补单
					await delay(timeLength);
					init_bet_count += 1;
					return await betOrderFun();
				}else {
					return {
						'state': 1,
						'data': res2,
						'message': 'Agreement suc',
					}
				}
			}else {
				storeLogs.add(JSON.stringify({'state':0,'code': 103, 'data': res2, 'agreement': 1}));
				if(error_bet_count <= bet_error_max_count) {
					await delay(timeLength);
					/// 失败需要重试
					error_bet_count += 1;
					console.error('Agreement 重试次数：' + error_bet_count);
					return await betOrderFun();
				}else {
					return {
						'code': 103,
						'state': 0,
						'message': 'Agreement FT_bet max_error',
						'data': res2,
					}
				}
			}
		} else {
			storeLogs.add(JSON.stringify({'state':0,'code': 104, 'data': res, 'agreement': 1}));
			if(error_bet_count <= bet_error_max_count) {
				await delay(timeLength);
				console.error('Agreement 重试次数：' + error_bet_count);
				error_bet_count += 1;
				return await betOrderFun();
			}else {
				return  {
					'code': 104,
					'state': 0,
					'data':  res,
					'message': 'Agreement FT_order_view max_error',
				}
			}
		}
	}
	return await betOrderFun();
}


let oldDate = "";
let dateList = [];
let ods = 1;
function getDayDate() {
	const newDate = formatTime(+new Date(), "YYYY-MM-DD");
	if(oldDate !== newDate) {
		dateList = [];
		for(var i=3;i>=0;i--) {
			let date = +new Date();
			date -= i * (1000 * 24 * 3600);
			dateList.push(formatTime(+new Date(date), "YYYY-MM-DD"));
		}
		oldDate = newDate;
	}
	if(dateList.length === 1) {
		let newHours = new Date().getHours();
		if(newHours <= 12) {
			let prevDay = +new Date(dateList[0]);
			prevDay -= (1000 * 24 * 3600);
			return formatTime(prevDay, "YYYY-MM-DD");
		}else if(newHours > 12 && newHours < 15) {
			if(ods === 1) {
				let prevDay = +new Date(dateList[0]);
				prevDay -= (1000 * 24 * 3600);
				ods = 2;
				return formatTime(prevDay, "YYYY-MM-DD");
			}else {
				ods = 1;
			}
		}
		return dateList[0];
	}
	return dateList.shift();
}

/**
 * 获取投注结果
 * @returns {Promise<*|*[]>}
 */
export const getOrderList = async function () {
	let userInfo = userInfoApi.get();
	const dateTime = getDayDate();
	const FT_order_view = {
		'p': 'history_switch',
		'uid': userInfo['uid'],
		'langx': userInfo['langx'],
		'LS': 'c',
		'today_gmt': dateTime,
		'gtype': 'FT',
		'tmp_flag': 'Y'
	}
	let res2 = await transformRequest(FT_order_view, userInfo['domain_url']);
	if (res2 && res2['wagers']) {
		let list = [];
		if(res2['wagers']['w_id']) {
			list.push(res2['wagers']);
		}else {
			list = res2['wagers'];
		}

		createHgaOrder({
			'time_str': res2['selDate'],
			'data': list,
			'new_user_name': configUserStore.setting.hga_user_name || "",
		})
		return list;
	}
	return [];
}

/**
 * 获取比赛详情盘口
 * @param competition
 * @returns {Promise<{state: number, message: string}>}
 */
export const getHgaGameInfo = async function(competition = {}){
	let userInfo = userInfoApi.get();
	if(!userInfo['uid']) {
		return {
			'state': 0,
			'message': 'userinfo empty'
		}
	}
	let FT_order_view = {
		'p': 'get_game_more',
		'uid': userInfo['uid'],
		'langx': userInfo['langx'],
		'ver': userInfo['ver'],
		'gtype': 'ft',
		'showtype': competition['diff_time_type'] === 'doing' ? 'live' : 'today',
		'ltype': userInfo['ltype'],
		'isRB': competition['diff_time_type'] === 'doing' ? 'Y' : 'N',
		'lid': competition['lid'],
		'specialClick':'',
		'mode': 'NORMAL',
		'filter':'Main',
		'ts': +new Date(),
		'ecid': competition['ecid'],
	};

	let res = await transformRequest(FT_order_view, userInfo['domain_url']);
	// console.log(['get_GameInfo', res]);
	// storeLogs.add(JSON.stringify(res));

}
